using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Redis_demo.Entities;
using Redis_demo.Result;
using StackExchange.Redis;
using Newtonsoft;
using Newtonsoft.Json;
using Mapster;

namespace Redis_demo.Controllers;

[Route("api/[controller]")]
public class ShopController : ControllerBase
{


    private readonly IConnectionMultiplexer _connectionMultiplexer;
    private readonly UserDbContext _userDbContext;

    public ShopController(IConnectionMultiplexer connectionMultiplexer,
        UserDbContext userDbContext)
    {
        _connectionMultiplexer = connectionMultiplexer;
        _userDbContext = userDbContext;
    }

    [HttpGet("shop")]
    public async Task<Result<Shop>> GetShops(string id)
    {
        // 1第一步从缓存中读取数据
        var dataBase = _connectionMultiplexer.GetDatabase();
        var shopJson = await dataBase.StringGetAsync("cache:shop:" + id);
        if (string.IsNullOrEmpty(shopJson))
        {
            // 1.1如果数据不存在 从数据库中读取
            var data = await _userDbContext.Shops.FirstOrDefaultAsync(x => x.Id == id);
            if(data == null){
                await dataBase.StringSetAsync("cache:shop:" + id,"");
                return Result<Shop>.Fail("商店不存在");
            }
            // 1.2添加到缓存中
            await dataBase.StringSetAsync("cache:shop:" + id, JsonConvert.SerializeObject(data));
            return Result<Shop>.SuccessRT(data);
        }
        else
        {
            // 缓存中读取的是null
            if(string.IsNullOrWhiteSpace(shopJson))
            {
                return  Result<Shop>.Fail(null);
            }
            // 1.2如果数据存在则直接返回
            var shop = JsonConvert.DeserializeObject<Shop>(shopJson.ToString());
            return Result<Shop>.SuccessRT(shop);
        }

    }

    [HttpGet("updateshop")]
    public async Task<Result<Shop>> UpdateShop(Shop shop)
    {
        // 1第一步从缓存中读取数据
        var dataBase = _connectionMultiplexer.GetDatabase();
        // 1.1更新数据
        var shopbydb = await _userDbContext.Shops.FirstAsync(x => x.Id == shop.Id);
        shopbydb.mark = shop.mark;
        shopbydb.Address = shop.Address;
        var data = _userDbContext.Shops.Update(shopbydb).Entity;
        // 1.2添加到缓存中
        await dataBase.StringGetDeleteAsync("cache:shop:" + shop.Id);
        return Result<Shop>.SuccessRT(data);
    }
}
